package net.sunbeta.test.database ;

import java.lang.reflect.Constructor ;
import java.lang.reflect.InvocationTargetException ;
import java.util.List ;
import java.util.Map ;

import org.apache.log4j.Logger ;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate ;

public class AbstractDAO {
    static final Logger                                                   log = Logger.getLogger(AbstractDAO.class) ;

    //spring fields
    private SimpleJdbcTemplate                                            template ;
    @SuppressWarnings("rawtypes")
    private Map<Class, Class< ? extends AbstractPreparedStatementSetter>> statementSetters ;

    //spring fields

    @SuppressWarnings("rawtypes")
    public int[] batchUpdate(String sql, List objects) {
        if (!objects.isEmpty()) {
            try {
                AbstractPreparedStatementSetter setter = getSetter(objects, objects.get(0).getClass()) ;
                if (setter != null) {
                    return template.getJdbcOperations().batchUpdate(sql, setter) ;
                }
            } catch (Exception e) {
                log.error("Error while construct sql setter", e) ;
            }
        }

        return new int[] {} ;
    }

    @SuppressWarnings("rawtypes")
    private AbstractPreparedStatementSetter getSetter(List objects, Class objectClazz) throws InvocationTargetException,
        IllegalAccessException, InstantiationException, NoSuchMethodException {
        Class< ? extends AbstractPreparedStatementSetter> setterClazz = statementSetters.get(objectClazz) ;

        if (setterClazz != null) {
            Constructor< ? extends AbstractPreparedStatementSetter> c = setterClazz.getConstructor(List.class) ;
            return c.newInstance(objects) ;
        } else {
            log.warn("======================NO SQL SETTER FOR CLASS " + objectClazz.getName() + "======================") ;
            return null ;
        }
    }
}
